<!-- <template>
  <div class="container-header-margin content">需求帮助
    <div ref="chatContainer"></div>
  </div>


</template>
  
<script setup>
import { useUserStore } from "@/store/user";
import { SYSYTM_TITLE } from "@/config";
 
const user = useUserStore();
useSeoMeta({
  title: "需求帮助-" + SYSYTM_TITLE,
  description: SYSYTM_TITLE,
  keywords: "白云学院,创新创业网",
  robots: "index, follow",
  canonical: "https://example.com",
});

const cozeWebSDK = new CozeWebSDK.WebChatClient({
  config: {
    botId: '7480476157490659379',
    isIframe: false,
  },
  auth:  {
    type: 'token',
    token: 'pat_AOZh3ZemQoBTSWZrSAzjlZ7S50lclMvv0SzB0rrHOQM8P2fnHF4lSTPOmECg1Aui',
    onRefreshToken: async () => 'pat_AOZh3ZemQoBTSWZrSAzjlZ7S50lclMvv0SzB0rrHOQM8P2fnHF4lSTPOmECg1Aui',
  },
  userInfo: {
      id: '123', //TODO 改成对应的用户信息
      url: 'https://lf-coze-web-cdn.coze.cn/obj/coze-web-cn/obric/coze/favicon.1970.png',
      nickname: '3qweqweqwe', //TODO 改成对应的用户信息
    },
    ui: {
      base: {
          icon: 'https://lf-coze-web-cdn.coze.cn/obj/coze-web-cn/obric/coze/favicon.1970.png',
          layout: 'pc',
          zIndex: 1000,
      },
      asstBtn: {
          isNeed: true,
      },
     
      }
    },
   
);
cozeWebSDK();
</script>
 -->
<!-- <template>
  <div id="chatContainer" style="position: absolute; top: 70px;height: calc(100vh - 105px)"></div>
 </template> -->
<!-- 
<script setup>
import { ref, onMounted, onBeforeUnmount } from "vue";
import { useUserStore } from "@/store/user";
import { SYSYTM_TITLE } from "@/config";

const user = useUserStore();



useSeoMeta({
  title: `需求帮助-${SYSYTM_TITLE}`,
  description: SYSYTM_TITLE,
  keywords: "白云学院,创新创业网",
  robots: "index, follow",
  canonical: "https://example.com",
});

const chatContainer = ref(null);
let cozeWebSDK = null;

// 仅在客户端执行
if (process.client) {
  const a = document.body.clientWidth
  onMounted(() => {
    try {
      // 检查 SDK 是否加载
      if (typeof CozeWebSDK === "undefined") {
        console.error("Coze SDK 未加载，请检查 CDN 链接");
        return;
      }

      // 初始化 Coze SDK
      cozeWebSDK = new CozeWebSDK.WebChatClient({
        config: {
          botId: "7480476157490659379",
          isIframe: false,
        },
        auth: {
          type: "token",
          token:
            "pat_AOZh3ZemQoBTSWZrSAzjlZ7S50lclMvv0SzB0rrHOQM8P2fnHF4lSTPOmECg1Aui",
          onRefreshToken: async () =>
            "pat_AOZh3ZemQoBTSWZrSAzjlZ7S50lclMvv0SzB0rrHOQM8P2fnHF4lSTPOmECg1Aui",
        },
        userInfo: {
          id: user.userId || "123", // 动态获取用户ID
          url: "https://lf-coze-web-cdn.coze.cn/obj/coze-web-cn/obric/coze/favicon.1970.png",
          nickname: user.nickname || "用户昵称", // 动态获取用户昵称
        },
        ui: {
          base: {
            icon: "https://lf-coze-web-cdn.coze.cn/obj/coze-web-cn/obric/coze/favicon.1970.png",
            layout: "PC",
            zIndex: 1000,
          },
          header: {
            isShow: true,
            isNeedClose: false
          },
          asstBtn: {
            isNeed: true,
          },
          footer: {
            isShow: true,
            expressionText: "Powered by {{name}}&{{name1}}",
            linkvars: {
              name: {
                text: "A",
                link: "https://www.test1.com",
              },
              name1: {
                text: "B",
                link: "https://www.test2.com",
              },
            },
          },
          chatBot: {
            title: "创新服务平台智能助手",
            uploadable: true,
            width: a,
            // height: 400,
            el: document.getElementById('chatContainer')
            // onHide: () => {
            //   // todo...
            // },
            // onShow: () => {
            //   // todo...
            // },
          },
        },
      });
      cozeWebSDK.showChatBot();

      // 挂载到DOM容器
      cozeWebSDK.mount(chatContainer.value);
    } catch (error) {
      console.error("Coze SDK 初始化失败:", error);
    }
  });

  onBeforeUnmount(() => {
    if (cozeWebSDK) {
      cozeWebSDK.destroy();
    }
  });
}
</script>

<style scoped>
</style> -->



<!-- //另一个项目搬过来的 -->
<template>
    <div class="outer">
      <div class="dialog">
        <div class="two">
          <div class="img">
            <img src="@/assets/img/logo.png" alt="" style="width: 100%" />
          </div>
          <div class="content">
            <div class="title" id="0" style="display: flex; flex-direction: row">
              {{ welcome }}
            </div>
            <div class="icon">
              <div class="copy">
                <svg-icon icon-name="copy"></svg-icon>
                <div style="margin-left: 5px" @click="copyDomText()">复制</div>
              </div>
            </div>
          </div>
        </div>
        <div v-for="(item, index) in contentArr" :key="index">
          <!-- 用户输出 -->
          <div class="one">
            <span>{{ item.inputtext }}</span>
          </div>
  
          <!-- AI 输出 -->
          <div class="two">
            <div class="img">
              <img src="@/assets/img/logo.png" alt="" style="width: 100%" />
            </div>
            <div class="content">
              <VueMarkdown class="title" style="display: flex; flex-direction: row" :source="item.restext">
              </VueMarkdown>
              <div class="icon">
                <div class="copy">
                  <svg-icon icon-name="copy"></svg-icon>
                  <div style="margin-left: 5px" @click="handleCopy(item.restext)">复制</div>
                </div>
                <div class="retry">
                  <svg-icon icon-name="retry"></svg-icon>
                  <div style="margin-left: 5px" @click="doItAgain">再试一次</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="input">
        <textarea placeholder="请输入内容" id="inputcon" class="prompt" v-model="prompt" @keyup.enter="send"></textarea>
        <div class="bottom">
          <div class="right">
            <a-button type="primary" :disabled="isContent" :loading="isSend" @click="send">
              <template #icon>
                <RightOutlined />
              </template>
            </a-button>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue';
  import clipBoard from "vue-clipboard3";
  import VueMarkdown from "vue-markdown-render";
  import { RightOutlined } from "@ant-design/icons-vue";
  
  
  let { toClipboard } = clipBoard(); // 一键复制
  
  // 欢迎语句
  const welcome = ref(
    "你好！请问有什么可以帮助你的？如果你有任何问题或者需要建议，请随时告诉我。"
  );
  
  // 用户输出内容
  const prompt = ref("");
  const isContent = ref(true);
  const isSend = ref(false);
  
  watch(prompt, (newValue, oldValue) => {
    if (prompt.value) {
      isContent.value = false;
    } else {
      isContent.value = true;
    }
  });
  
  // 复制功能
  const copyDomText = () => {
    const titleElement = document.getElementById("0");
    if (titleElement) {
      const text = titleElement.innerText;
      navigator.clipboard
        .writeText(text)
        .then(() => {
          message.success("复制成功");
        })
        .catch((err) => {
          message.error("复制失败");
        });
    }
  };
  
  // 内容数组
  const contentArr = ref<Array<{ inputtext: string; restext: string }>>([]);
  
  // 一键复制
  const handleCopy = async (str: string) => {
    try {
      await toClipboard(str);
      message.success("复制成功");
    } catch (e) {
      message.error("复制失败");
    }
  };
  
  // 刷新功能
  const doItAgain = () => {
    prompt.value = contentArr.value[contentArr.value.length - 1].inputtext;
    contentArr.value.pop();
    isSend.value = false;
    send();
  };
  
  const send = async () => {
    if (!prompt.value) return;
    isSend.value = true;
  
    const newItem = reactive({
      inputtext: prompt.value,
      restext: "",
    });
    contentArr.value.push(newItem);
  
    try {
      const response = await fetch("http://81.71.154.186:8088/ali/chat/stream", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ prompt: prompt.value }),
      });
      prompt.value = "";
  
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
  
      const reader = response.body.getReader();
      const decoder = new TextDecoder();
      const lastItem = contentArr.value[contentArr.value.length - 1];
      const messageQueue = [];
  
      const printMessage = async (message) => {
        for (let i = 0; i < message.length; i++) {
          lastItem.restext += message[i];
          await new Promise((resolve) => setTimeout(resolve, 10));
        }
      };
  
      while (true) {
        const { done, value } = await reader.read();
        if (done) {
          isSend.value = false;
          break;
        }
  
        const chunk = decoder.decode(value, { stream: true });
        const lines = chunk.split("\n");
        lines.forEach((line) => {
          const trimmedLine = line.trim();
          if (trimmedLine.startsWith("data:")) {
            const data = trimmedLine.substring(5).trim();
            if (data) {
              messageQueue.push(data);
            }
          } else if (!trimmedLine.startsWith("event:")) {
            const data = trimmedLine.trim();
            if (data) {
              messageQueue.push(data);
            }
          }
        });
  
        while (messageQueue.length > 0) {
          const message = messageQueue.shift();
          await printMessage(message);
        }
      }
    } catch (error) {
      isSend.value = false;
      console.error("请求失败:", error);
      alert("请求失败，请检查网络或重试！");
    }
  };
  </script>
  
  <style lang="less" scoped>
  * {
    margin: 0;
    padding: 0;
  }
  
  .outer {
    display: flex;
    flex-direction: column;
    overflow-y: hidden;
    overflow-x: hidden;
  }
  
  .dialog {
    overflow-y: auto;
    max-height: 64vh;
    border-radius: 20px;
  }
  
  .one {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 60px;
  }
  
  .one span {
    display: inline-block;
    border-block: 7px;
    background-color: #f0f0f0;
    text-align: right;
    height: 40px;
    line-height: 40px;
    padding: 4px 20px;
    border-radius: 20px;
  }
  
  .two {
    display: flex;
    justify-content: flex-start;
  }
  
  .two .img {
    display: flex;
    flex-wrap: wrap;
    align-content: center;
    justify-content: center;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    margin-right: 3px;
  }
  
  .two .content {
    background-color: #f0f0f0;
    border-radius: 20px;
    width: 700px;
  }
  
  .two .title {
    border-block: 7px;
    text-align: left;
    padding: 4px 20px 0 20px;
    word-wrap: break-word;
    line-height: 1.5;
    white-space: normal;
  }
  
  .icon {
    display: flex;
    margin: 10px;
    margin-top: 0;
    cursor: pointer;
  }
  
  .copy,
  .retry {
    display: flex;
    align-items: center;
    margin-left: 5px;
    padding: 2px;
    color: rgb(94 103 114);
  }
  
  .copy:hover,
  .retry:hover {
    background-color: rgb(94 103 114 / 35%);
    color: black;
    border-radius: 5px;
  }
  
  svg-icon {
    margin-right: 5px;
  }
  
  .input {
    background-color: #fff;
    position: fixed;
    bottom: 0px;
    width: 95%;
    height: 180px;
    border-radius: 20px;
    padding-left: 10px;
    padding-top: 10px;
  }
  
  .prompt {
    width: 100%;
    height: 100%;
    border: none;
    background-color: transparent;
    font-size: 18px;
    color: #000;
    outline: none;
    border-radius: 20px;
    padding: 10px;
  }
  
  .input .bottom {
    position: fixed;
    bottom: 20px;
    display: flex;
    margin: 5px;
    width: 90%;
    justify-content: space-between;
    flex-direction: row-reverse;
  }
  
  .line,
  .send {
    margin-right: 10px;
    cursor: pointer;
  }
  
  .send {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 20px;
    height: 20px;
    border-radius: 10px;
    background-color: #ccc;
    position: absolute;
    right: 0;
    bottom: 0;
    padding: 5px;
  }
  
  ::-webkit-scrollbar {
    width: 10px;
    height: 10px;
  }
  
  ::-webkit-scrollbar-track {
    width: 6px;
    background: rgba(#101f1c, 0.1);
    border-radius: 2em;
  }
  
  ::-webkit-scrollbar-thumb {
    background-color: rgba(144, 147, 153, 0.5);
    border-radius: 2em;
    transition: background-color 0.3s;
    cursor: pointer;
  }
  
  ::-webkit-scrollbar-thumb:hover {
    background-color: rgba(144, 147, 153, 0.3);
  }
  </style>